/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.jni.SSLConf;
import web.enity.UserInfo;
import web.exception.AccountNotFoundException;
import web.exception.IncorrectPasswordException;
import web.service.Impl.UserServiceImpl;
import web.service.UserService;

/**
 *
 * @author 10592
 */
public class LoginServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");     
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        if (request.getParameter("flag")==null) {
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
        else{
            int action = Integer.valueOf(request.getParameter("flag"));
            switch (action) {
                case 1:
                    login(request, response);
                    break;
                case 2:
                    resiger(request, response);
                    break;
                case 3:
                    checkEmail(request, response);
                    break;
                case 4:
                    checkRePassword(request, response);
                    break;
                case 5:
                    checkUserAccount(request, response);
            }
        }
        
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.;
           PrintWriter out = response.getWriter();
           // 获取客户端的输入
           String userName = request.getParameter("userName");
           String passWord = request.getParameter("passWord");
           System.out.println(userName+"\t"+passWord);
           // 调用业务逻辑
           UserService us =new UserServiceImpl();
           // 封装user对象
            UserInfo userInfo = new UserInfo(userName, passWord);
            UserInfo userFromDB =null;
           try {
               userFromDB= us.Login(userInfo); ;
            } catch (AccountNotFoundException e) {
                System.out.println("用户不存在");
                out.write("用户不存在");
                out.close();
            }catch(IncorrectPasswordException e){
                out.write("密码不正确");
                out.close();
            }
          
         
           if (userFromDB!=null) {
               
               //存cookie   服务端产生，保存在客户端    建议cookie只保存英文和数字
               Cookie ckUsername = new Cookie("username", userName);
               Cookie ckPassword = new Cookie("pwd", passWord);
               ckPassword.setMaxAge(120);
               ckUsername.setMaxAge(120);
               response.addCookie(ckUsername);
               response.addCookie(ckPassword);

               //将登陆成功的用户信息保存到session（服务端 内置对象 在同一个用户（客户端）请求书共享 ）
               HttpSession session = request.getSession();
               session.setAttribute("Login_USER", userInfo);
               UserInfo userInfo1 = (UserInfo) session.getAttribute("Login_USER");
               System.out.println("用户名"+userInfo1.getUserName());
               out.print("success");
            } else {
               out.print(false);
               request.getRequestDispatcher("login.jsp").forward(request, response);
            }

       
    }

    private void resiger(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        UserService us = new UserServiceImpl();
        PrintWriter out = response.getWriter();
        String passWord = request.getParameter("passWord");
        String email = request.getParameter("email");
        String userName = request.getParameter("userName");
        String rePassWord = request.getParameter("rePassWord");
        if (userName!=null&&passWord!=null&&rePassWord!=null&&email!=null) {
            UserInfo ui = new UserInfo(userName, passWord, email);
            if (us.Resiger(ui)==1) {
                response.sendRedirect("register_success.html");
            } else {
                request.getRequestDispatcher("register.jsp").forward(request, response);
            }
        } else {
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }

    private String checkEmail(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String email = request.getParameter("email");
        PrintWriter out = response.getWriter();
        if (email!=null) {
            String check = "^([a-z0-9A-Z]+[-1\\.]?)+([a-z0-9A-Z]@[a-z0-9A-Z]+(-[a-z0-9A-Z]+)" + "?\\.)+[a-zA-Z]{2,}$";
            if (email.matches(check)) {
                out.write("邮箱输入正确");
                out.flush();
                out.close();
                return email;
            } else {
                out.write("邮箱输入不正确");
                out.flush();
                out.close();
                return null;
            }
        }else
            return null;
        
    }

    private String checkRePassword(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String rePassWord = request.getParameter("rePassWord");
        String passWord = request.getParameter("passWord");
        PrintWriter out = response.getWriter();
        if (passWord!=null&&rePassWord!=null) {
            if (passWord.equals(rePassWord)) {
                out.write("两次密码输入一致");
                out.flush();
                out.close();
                return rePassWord;
            } else {
                out.write("两次密码输入不一致");
                out.flush();
                out.close();
                return null;
            }
        }else
            return null;
       
    }

    private String checkUserAccount(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
        UserService us = new UserServiceImpl();
        PrintWriter out = response.getWriter();
        String userName = request.getParameter("userName");
        if (userName!=null) {
            if (us.getAll(userName) == 1) {
                System.out.println("用户存在");
                out.write("用户存在");
                out.flush();
                out.close();
                return null;
            } else {
                System.out.println("用户不存在");
                out.write("用户不存在");
                out.flush();
                out.close();
                return userName;
            }
        }else
            return null;
       
      
    }

}
